package service

import (
	"fmt"
	log "github.com/sirupsen/logrus"
	"runtime"
	"strings"
	"sync"
	"usbipproxy/domain/vo"
)

type DeviceService interface {
	GetDeviceInfo(vid, pid string) []*vo.DeviceInfo
}

type DeviceCacheService interface {
	SetDeviceInfo(vid, pid string, val []*vo.DeviceInfo)
	GetDeviceInfo(vid, pid string) []*vo.DeviceInfo
	NeedUpanSkip(name string) bool
}

type DeviceCacheServiceImpl struct {
	rwLock        sync.RWMutex
	infoMap       map[string][]*vo.DeviceInfo
	upanSkipWords []string
}

func (d *DeviceCacheServiceImpl) GetKey(vid, pid string) string {
	return fmt.Sprintf("%s:%s", vid, pid)
}

func (d *DeviceCacheServiceImpl) GetDeviceInfo(vid, pid string) []*vo.DeviceInfo {
	d.rwLock.RLock()
	defer d.rwLock.RUnlock()
	return d.infoMap[d.GetKey(vid, pid)]
}

func (d *DeviceCacheServiceImpl) NeedUpanSkip(name string) bool {
	for _, skipWord := range d.upanSkipWords {
		if strings.Contains(strings.ToLower(name), skipWord) {
			return true
		}
	}

	return false
}

func (d *DeviceCacheServiceImpl) SetDeviceInfo(vid, pid string, val []*vo.DeviceInfo) {
	d.rwLock.Lock()
	defer d.rwLock.Unlock()
	d.infoMap[d.GetKey(vid, pid)] = val
}

func NewDeviceCacheServiceImpl(upanSkipWord string) DeviceCacheService {

	var upanSkipWors []string
	upanSkipWords := strings.Split(upanSkipWord, ",")
	for _, v := range upanSkipWords {
		if v != "" {
			upanSkipWors = append(upanSkipWors, strings.ToLower(v))
		}
	}

	return &DeviceCacheServiceImpl{
		infoMap:       make(map[string][]*vo.DeviceInfo),
		upanSkipWords: upanSkipWors,
	}
}

var DeviceServiceFactoryObj = &DeviceServiceFactory{}

type DeviceServiceFactory struct{}

func (f *DeviceServiceFactory) Create(upanSkipWord string) DeviceService {
	os := runtime.GOOS
	switch os {
	case "windows":
		log.Infof("当前是 Windows 系统")
		return NewDeviceWindowsService(upanSkipWord)
	case "linux":
		log.Infof("当前是 Linux 系统")
		return NewDeviceLinuxService(upanSkipWord)
	default:
		log.Infof("当前是其他系统：%s\n", os)
	}
	return nil
}
